import requests
import json

def get_token(huawei_cloud_access_key, huawei_cloud_secret_key, region):
    auth_url = f"https://iam.{region}.myhuaweicloud.com/v3/auth/tokens"
    auth_data = {
        "auth": {
            "identity": {
                "methods": ["password"],
                "password": {
                    "user": {
                        "name": huawei_cloud_access_key,
                        "password": huawei_cloud_secret_key,
                        "domain": {
                            "name": huawei_cloud_access_key
                        }
                    }
                }
            },
            "scope": {
                "project": {
                    "name": region
                }
            }
        }
    }
    response = requests.post(auth_url, json=auth_data)
    if response.status_code == 201:
        token = response.headers['X-Subject-Token']
        return token
    else:
        print("Failed to get token:", response.text)
        return None


def create_or_update_ip_address_group(token, region, project_id, group_name, ip_addresses):
    url = f"https://vpc.{region}.myhuaweicloud.com/v1/{project_id}/ip_address_groups"
    headers = {
        "Content-Type": "application/json",
        "X-Auth-Token": token
    }

    # 检查是否已存在该 IP 地址组
    response = requests.get(url, headers=headers)
    if response.status_code == 200:
        groups = response.json().get('ip_address_groups', [])
        existing_group = next((g for g in groups if g['name'] == group_name), None)

        if existing_group:
            # 更新现有 IP 地址组
            update_url = f"https://vpc.{region}.myhuaweicloud.com/v1/{project_id}/ip_address_groups/{existing_group['id']}"
            update_payload = {
                "ip_address_group": {
                    "name": group_name,
                    "ip_addresses": ip_addresses
                }
            }
            response = requests.put(update_url, headers=headers, data=json.dumps(update_payload))
            if response.status_code == 200:
                print("IP address group updated successfully.")
            else:
                print("Failed to update IP address group:", response.text)
        else:
            # 创建新的 IP 地址组
            create_payload = {
                "ip_address_group": {
                    "name": group_name,
                    "ip_addresses": ip_addresses
                }
            }
            response = requests.post(url, headers=headers, data=json.dumps(create_payload))
            if response.status_code == 201:
                print("IP address group created successfully.")
            else:
                print("Failed to create IP address group:", response.text)
    else:
        print("Failed to get IP address groups:", response.text)


if __name__ == "__main__":
    huawei_cloud_access_key = "PABSH8UFFMNKLJY6UZTN"
    huawei_cloud_secret_key = "jbNhDn6YLYvtYgHfVeRX6lqLkmqRa382t6u9BwjX"
    region = "cn-north-4"  # 你的区域
    project_id = "0e96b353e18090f12fa2c00d90e1d0f4"  # 你的项目 ID
    group_name = "ipGroup-2eca"
    ip_addresses = ["192.168.1.1/32", "192.168.1.2/32"]  # 你的 IP 地址列表

    token = get_token(huawei_cloud_access_key, huawei_cloud_secret_key, region)
    if token:
        create_or_update_ip_address_group(token, region, project_id, group_name, ip_addresses)